<?php
    /**
    * 短信发送工具
    */
  class sms{
      private $appid = '1400178987';
      private $appkey = 'aa15e9deb38a3d0d6d61aadadbd57292';
      function sendWithParam($nationCode, $phoneNumber, $templId = 0, $params,$sign = "", $extend = "", $ext = ""){
            $random = rand(100000, 999999);
            $curTime = time();
            $wholeUrl = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=" . $this->appid . "&random=" . $random;
            $tel['nationcode'] = "".$nationCode;
            $tel['mobile'] = "".$phoneNumber;
            $dataObj['tel'] = $tel;
            $dataObj['sig'] = $this->calculateSig($this->appkey,$random,$curTime,$phoneNumber);
            $dataObj['tpl_id'] = $templId;
            $dataObj['params'] = $params;
            $dataObj['sign'] = $sign;
            $dataObj['time'] = $curTime;
            $dataObj['extend'] = $extend;
            $dataObj['ext'] = $ext;            
            return $this->sendCurlPost($wholeUrl,$dataObj);
            
            
      }
      /**
         * 发送请求
         *
         * @param string $url      请求地址
         * @param array  $dataObj  请求内容
         * @return string 应答json字符串
         */
        function sendCurlPost($url, $dataObj)
        {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($dataObj));
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
            $ret = curl_exec($curl);
            if (false == $ret) {
                // curl_exec failed
                $result = "{ \"result\":" . -2 . ",\"errmsg\":\"" . curl_error($curl) . "\"}";
            } else {
                $rsp = curl_getinfo($curl, CURLINFO_HTTP_CODE);
                if (200 != $rsp) {
                    $result = "{ \"result\":" . -1 . ",\"errmsg\":\"". $rsp
                            . " " . curl_error($curl) ."\"}";
                } else {
                    $result = $ret;
                }
            }
            curl_close($curl);
            return $result;
        }
        /**
        * 生成签名
        * 
        * @param mixed $appkey
        * @param mixed $random
        * @param mixed $curTime
        * @param mixed $phoneNumber
        */
        function calculateSig($appkey, $random, $curTime, $phoneNumber){            
            return hash("sha256", "appkey=".$appkey."&random=".$random
            ."&time=".$curTime."&mobile=".$phoneNumber);
        }
  }
?>
